package com.ruike.alisurface.mqtt;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.L;

/**
 * Author：voodoo
 * CreateTime：2021/03/22 022 10:38 上午
 * Description：服务的工具类
 */
public class ServiceUtils {

    public ServiceUtils() {
        throw new UnsupportedOperationException("不可以创建此类...");
    }

    /**
     * 查询所有运行中的服务
     *
     * @return 正在运行的服务
     */
    public static Set<String> getAllRunningServices(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> infos = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (infos == null || infos.size() <= 0) {
            return null;
        }
        Set<String> names = new HashSet<>();
        for (ActivityManager.RunningServiceInfo info : infos) {
            names.add(info.service.getClassName());
        }
        return names;
    }

    /**
     * 启动一个服务
     *
     * @param clazz 服务
     */
    public static void startService(Context context, @NonNull final Class<?> clazz) {
        try {
            context.startService(new Intent(context, clazz));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动一个服务
     *
     * @param clazz 服务
     */
    public static void stopService(Context context, @NonNull final Class<?> clazz) {
        try {
            context.stopService(new Intent(context, clazz));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isServiceRunning(Context context, String serviceName) {
        if (context == null || TextUtils.isEmpty(serviceName)) {
            return false;
        }
        try {
            Set<String> allRunningServices = getAllRunningServices(context);
            if (allRunningServices == null || allRunningServices.size() <= 0) {
                return false;
            }
            for (String serviceNameStr : allRunningServices) {
                if (serviceName.equals(serviceNameStr)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

}
